package com.fly.test.restful.json;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.List;

import org.apache.commons.io.IOUtils;
import org.junit.jupiter.api.Test;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class ParseJsonIgnoreError
{
    /**
     * thread-safe
     */
    ObjectMapper mapper = new ObjectMapper();
    
    /**
     * 解析为实体
     * 
     * @throws IOException
     */
    @Test
    public void testToEntity()
        throws IOException
    {
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) // 无法识别字段是否快速失败
            .readValue(getJsonData(), BlogDataBean.class)
            .getData()
            .getList()
            .stream()
            .forEach(article -> log.info("{} ", article));
    }
    
    /**
     * 获取jsonData
     * 
     * @return
     * @throws IOException
     */
    private String getJsonData()
        throws IOException
    {
        Resource resource = new ClassPathResource("data.json");
        try (InputStream input = resource.getInputStream())
        {
            return IOUtils.toString(input, StandardCharsets.UTF_8);
        }
    }
}

@Data
class BlogDataBean
{
    private Records data;
}

@Data
class Records
{
    private List<Article> list;
}

@Data
class Article
{
    String title;
    
    String url;
    
    Long viewCount;
}
